package com.bwei.mypaot.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

/**
 * Created by Administrator on 2017/2/20.
 */

public class Image extends ImageView {


    Paint paint;

    private Drawable drawable;
    public Image(Context context) {
        super(context);
    }

    public Image(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public Image(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        //获得图片资源
        Drawable drawable = getDrawable();
        if (null!=drawable){
            //获得图片
            Bitmap bitmap=((BitmapDrawable)drawable).getBitmap();

            Bitmap b=getRoundRextBitmap(bitmap);
            /**
             * 0，0，表示离里面的b的距离，左边距离和上边距离
             *   canvas.drawBitmap(b,rectSrc,rectDest,paint);
             */
            canvas.drawBitmap(b,0,0,null);

        }else{
            super.onDraw(canvas);
        }

    }

    public Bitmap getRoundRextBitmap(Bitmap bitmap){

        //得到控件的宽高
        int width=getWidth();
        int height=getHeight();
        Log.d("iii","width"+width+"height"+height);


        //取圆角正方形的边长，取屏幕边长的最短边

        int r=width>height?width:height;

        //矩形显示需要创建一个新图片，然后放在画布上，否则无法操作画布
        Bitmap background=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);

        Canvas canvas=new Canvas(background);

        paint=new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.WHITE);

        //画圆
        canvas.drawCircle(getWidth()/2,getHeight()/2,width/2,paint);

        //设置正方形，左上右下


        RectF rect=new RectF(0,0,r,r);
        // 设置当两个图形相交时的模式，SRC_IN为取SRC图形相交的部分，多余的将被去掉
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        //使图片和矩形交叉
        canvas.drawBitmap(bitmap,null,rect,paint);

        return background;
    }

}
